package com.muqi.app.qlearn.fragments;

import static nl.qbusict.cupboard.CupboardFactory.cupboard;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.contants.MContants;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.BitmapUtils;
import com.muqi.app.project.utils.LogUtil;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.modles.TreeHomeBean;
import com.muqi.app.qlearn.student.BaseChildFragment;
import com.muqi.app.qlearn.student.MenuActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.qlearn.ui.MyHomeWkDetailsActivity;
import com.muqi.app.user.db.ChildBean;
import com.muqi.app.user.db.MyClassStudent;
import com.muqi.app.user.db.TreeLeaf;
import com.muqi.app.user.widget.ClassWithStudentsWindow;

@SuppressWarnings("deprecation")
public class TabGrow extends BaseChildFragment implements OnClickListener, ClassWithStudentsWindow.SelectCWithSListener {
	private AbsoluteLayout mTreeRl;
	private AbsoluteLayout.LayoutParams params;
	private TreeRefreshReceiver receiver = null;

	private int[] locationX = new int[] { 234, 415, 247, 478, 207, 333, 253, 509, 274,
			204, 443, 418, 398, 284, 475, 290, 467, 227, 480, 293, 184, 454,
			391, 309, 237, 396, 279, 442, 435, 512, 179, 438, 499, 224, 512,
			208, 464, 195, 474, 399, 304, 238, 287, 442, 232, 319, 151, 363,
			175, 453, 498, 394, 248, 478, 279, 278, 406, 215, 318, 157, 446,
			546, 193, 534, 149, 519, 587, 138, 405, 214, 512, 177, 524, 266,
			254, 445, 521, 495, 117, 116, 560, 211, 265, 547, 372, 109, 495,
			152, 563, 304, 481, 152, 516, 148, 307, 551, 186, 153, 275, 555,
			137, 559, 524, 448, 183, 424, 118, 605, 585, 301, 102, 289, 560,
			177, 595, 316, 51, 523, 600, 178, 282, 642, 79, 126, 594, 168, 370,
			440, 107, 603, 205, 211, 414, 217, 594, 136, 613, 176, 267, 630,
			72, 56, 591, 262, 479, 409, 74, 402, 0, 161, 539, 256, 656, 479,
			226, 124, 225, 90, 643, 55, 14, 94, 622, 661, 279, 98, 351, 369,
			350, 643, 22, 29, 257, 500, 13, 640, 66, 608, 395, 293, 34, 65, 9,
			154, 316, 678, 280, 127, 74, 106, 451, 107, 323, 621, 199, 341,
			519, 302, 27, 652, 28, 577, 244, 358, 425, 304 };
	private int[] locationY = new int[] { 594, 321, 353, 600, 485, 510, 646, 559, 638,
			429, 507, 650, 420, 653, 377, 441, 659, 505, 462, 421, 410, 623,
			316, 508, 519, 549, 608, 599, 418, 499, 481, 354, 517, 328, 420,
			566, 335, 332, 497, 462, 458, 532, 396, 310, 649, 430, 483, 234,
			373, 485, 657, 510, 298, 338, 370, 332, 292, 622, 248, 406, 271,
			484, 308, 611, 515, 359, 530, 386, 257, 297, 612, 531, 566, 275,
			536, 446, 262, 250, 390, 334, 446, 646, 230, 567, 204, 357, 467,
			299, 374, 298, 300, 555, 226, 270, 160, 601, 645, 578, 118, 261,
			235, 470, 190, 179, 254, 146, 528, 563, 564, 187, 300, 134, 212,
			620, 595, 124, 304, 160, 277, 153, 198, 211, 331, 562, 324, 231,
			116, 219, 500, 497, 178, 260, 178, 219, 463, 522, 205, 122, 152,
			448, 430, 381, 427, 93, 138, 202, 513, 149, 514, 644, 122, 185,
			272, 84, 91, 632, 43, 380, 576, 576, 377, 238, 323, 545, 27, 202,
			156, 61, 49, 484, 455, 559, 53, 74, 539, 321, 208, 366, 91, 54,
			277, 590, 480, 106, 63, 452, 94, 109, 442, 602, 71, 145, 14, 411,
			70, 19, 99, 206, 335, 382, 413, 166, 29, 141, 77, 0 };
	
	private int[] fruitsLocationX = new int[]{246,475,213,166,501};
	private int[] fruitsLocationY = new int[]{149,255,299,487,474};
	private String[] fruitsGradeText = new String[]{"1级","1级","1级","1级","1级"};
	
	private AssetManager manager;
	private boolean hasMeasured = false;
	
	private double radioX;
	private double radioY;
	int height;
	int width;
	private ImageButton changeButton;
	
	private TextView treeTitle;
	private TextView treeDe;
	private TextView treeZhi;
	private TextView treeTi;
	private TextView treeMei;
	private TextView treeLao;
	private TextView leafTxt;
	
	private int leafNum = 0;
	private boolean isVisibility = true;
	private ImageView treeFeel;
	private ClassWithStudentsWindow myStudentsWindow = null;
	
	private int oldTreeLeft=-1; // 表示是第一次加载数据

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		oldTreeLeft=getArguments().getInt("oldTreeLeaf", -1);	
	}

	@SuppressLint("InflateParams") @Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.tree, null);
		mTreeRl = (AbsoluteLayout) view.findViewById(R.id.tree_rl);
		
		treeFeel=(ImageView) view.findViewById(R.id.treeFeel);
		
		
		manager = getActivity().getAssets();
		ViewTreeObserver vto = mTreeRl.getViewTreeObserver();
		vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {

			@Override
			public boolean onPreDraw() {
				// 只需要加载一次即可
				if (!hasMeasured) {
					height = mTreeRl.getMeasuredHeight();
					width = mTreeRl.getMeasuredWidth();

					radioX = width * 1.0 / 700;
					radioY = height * 1.0 / 832;
					// 控件的位置，暂时不需要
					// int x2 = (int) mTreeRl.getX();
					// int y2 = (int) mTreeRl.getY();

					// 获取到宽度和高度后，可用于计算
					LogUtil.e("控件的宽高为：" + width + "................" + height);
					// LogUtil.e("控件的位置为：" + x2 + "................" + y2);
					LogUtil.e("控件的比率为：" + radioX + "................" + radioY);
					
					hasMeasured = true;
				}
				return true;
			}
		});
		changeButton = (ImageButton)view.findViewById(R.id.changeButton);
		changeButton.setOnClickListener(this);
		
		treeTitle = (TextView)view.findViewById(R.id.tree_title);
		treeDe = (TextView)view.findViewById(R.id.tree_text_de);
		treeZhi = (TextView)view.findViewById(R.id.tree_text_zhi);
		treeTi = (TextView)view.findViewById(R.id.tree_text_ti);
		treeMei = (TextView)view.findViewById(R.id.tree_text_mei);
		treeLao = (TextView)view.findViewById(R.id.tree_text_lao);
		leafTxt = (TextView)view.findViewById(R.id.tree_text_leaf);
		
		if(mSpUtil.getUserType().equals(MContants.LOGIN_AS_PARENTS)){
			if(currentChild!=null){
				treeTitle.setText(currentChild.name);
				treeTitle.setOnClickListener(this);
				setMyclassStudentsWindow(currentChild);
			}
		}
		
		MenuActivity parentAct = (MenuActivity) getActivity();
		if (parentAct != null) {
			parentAct.dismissBackgroundImg();
		}
		return view;
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		receiver = new TreeRefreshReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MContants.CHANGE_CURRENT_CHILD_ACTION);
		getActivity().registerReceiver(receiver, filter);
		
		loadingGrowTreeDatas();
	}
	
	private boolean isNewLeafsShow(){
		boolean show=true; // 默认已经显示过
		TreeLeaf leaf=cupboard().withDatabase(sqlDb).query(TreeLeaf.class)
		.withSelection("child_id = ?", mSpUtil.getCurrentChildId()).get();
		if(leaf!=null){
		    show=leaf.hasShow;
		}
		return show;
	}
	 
	 
	 @Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		LogUtil.e("growTree回调值为"+hidden);
		isVisibility = !hidden;
		if(!hidden){
			
			loadingGrowTreeDatas();
		}
	}
	 
	private void showOldLeafs(int oldNum){
		for(int i=0;i<oldNum;i++){
			leafNum++;
			if (leafNum < locationX.length) {
				addLeafWithoutAnimation(leafNum);
			}
		}
	}
	
	private void showNewLeafs(int needAnimationNum){
		for(int i=0;i<needAnimationNum;i++){
			leafNum++;
			if (leafNum < locationX.length) {
				addLeafWithAnimation(leafNum);
			}
		}
	
			
			ContentValues contentValues=new ContentValues();
			contentValues.put("hasShow", true);
			cupboard().withDatabase(sqlDb).update(TreeLeaf.class, contentValues,"child_id = ?", mSpUtil.getCurrentChildId());
			MenuActivity parentAct = (MenuActivity)getActivity();
			if(parentAct!=null){
				parentAct.updateTreeLabel();
			}
		/*if(needAnimationNum>0){
			cupboard().withDatabase(sqlDb).delete(TreeLeaf.class, "child_id = ?", 
					mSpUtil.getCurrentChildId());
			
			MenuActivity parentAct = (MenuActivity)getActivity();
			if(parentAct!=null){
				parentAct.updateTreeLabel();
			}
		}*/
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
	
		case R.id.changeButton:
			/*MenuActivity parentAct = (MenuActivity)getActivity();
			if(parentAct!=null){
				parentAct.changeTreeFragment(true);
			}*/
			break;
		case R.id.tree_title:
//			if(myStudentsWindow!=null){
//				myStudentsWindow.showPopupWindow(v);
//			}
			showChildrenWindow(v);
			break;
		default:
			break;
		}
	}
	
	private void addFruits(final int i) {
		View fruits = View.inflate(getActivity(), R.layout.tree_branch, null);
		fruits.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//Toast.makeText(getActivity(), "点击了"+fruitsGradeText[i-1], Toast.LENGTH_SHORT).show();
			
			}
		});
		ImageView fruitsImage = (ImageView) fruits.findViewById(R.id.fruits_iv);
		TextView fruitsGrade = (TextView) fruits.findViewById(R.id.fruits_tv);
		try {
			InputStream in = manager.open("treefruits/" + i + ".png");
			bitmap = BitmapFactory.decodeStream(in);
			bitmap = BitmapUtils.scaleImage(bitmap,
					((int) (bitmap.getWidth() * radioX)),
					((int) (bitmap.getHeight() * radioY)));
		} catch (Exception e) {
			LogUtil.e("出现异常，未加载到资源图片");
		}

		if (bitmap != null) {
			fruitsImage.setImageBitmap(bitmap);
		}
		fruitsGrade.setText(fruitsGradeText[i-1]);
		params = new AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT, (int) (fruitsLocationX[i - 1] * radioX),
				(int) (fruitsLocationY[i - 1] * radioY));

		fruits.setLayoutParams(params);
		mTreeRl.addView(fruits, params);
	}
	
	
	private void addLeafWithAnimation(int num) {
		ImageView imageView = addLeaf(num);
		ObjectAnimator scaleY = ObjectAnimator.ofFloat(imageView, "scaleY", 1f,
				2f, 1f);
		ObjectAnimator scaleX = ObjectAnimator.ofFloat(imageView, "scaleX", 1f,
				2f, 1f);
		AnimatorSet animSet = new AnimatorSet();
		animSet.play(scaleX).with(scaleY);
		animSet.setDuration(3000);
		animSet.start();
	}

	private void addLeafWithoutAnimation(int num) {
		addLeaf(num);
	}

	Bitmap bitmap = null;

	private ImageView addLeaf(int num) {
		try {
			InputStream in = manager.open("treepic/" + num + ".png");
			bitmap = BitmapFactory.decodeStream(in);
			bitmap = BitmapUtils.scaleImage(bitmap,
					((int) (bitmap.getWidth() * radioX)),
					((int) (bitmap.getHeight() * radioY)));
		} catch (Exception e) {
			LogUtil.e("出现异常，未加载到资源图片");
		}

		ImageView imageView = new ImageView(getActivity());
		if (bitmap != null) {
//			LogUtil.e("bitmap生成了，，，，，，，，，，，" + num);
			imageView.setImageBitmap(bitmap);
		}

		params = new AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT, (int) (locationX[num - 1] * radioX),
				(int) (locationY[num - 1] * radioY));

		imageView.setLayoutParams(params);

		mTreeRl.addView(imageView, params);

		// if (bitmap != null && !bitmap.isRecycled()){
		// bitmap.recycle();
		// bitmap = null;
		// }
		return imageView;
	}
	/**
	 * 参数说明：如果和年级比，班级id传0，
		班级id不为0就是和班级比较
		学生id号码必传。以下接口说明一致。
	 * @param myChild
	 */
	public void loadingGrowTreeDatas() {
		if (NetWorkUtils.isNetworkAvailable(getActivity())) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("token", mSpUtil.getToken());
			sendMap.put("class_manager_id", mSpUtil.getChildClassId());
			sendMap.put("grade_id", mSpUtil.getChildGradeId());
			sendMap.put("school_id", mSpUtil.getChildSchoolId());
			sendMap.put("student_id", mSpUtil.getCurrentChildId());
			String requestUrl = ParamsUtils.buildParams(NetWorkApi.GET_GROW_TREE_DATAS, sendMap);
			MyAsyncHttp.get(getActivity(), requestUrl, new AsyncCallBackListener() {
				
				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode, String request, String result) {
					if(resuleCode == RESULTCODE.SUCCESS){
						TreeHomeBean getData = ResponseUtils.getTreeHomeDatas(getActivity(), result);
						if(getData!=null){
							
							
							treeDe.setText(getData.F1count);
							treeZhi.setText(getData.F2count);
							treeTi.setText(getData.F3count);
							treeMei.setText(getData.F4count);
							treeLao.setText(getData.F5count);
							leafTxt.setText(getData.peibancount);
							
							mTreeRl.removeAllViews();
							leafNum = 0;
							if("cry".equals(getData.feeling)){
								treeFeel.setImageResource(R.drawable.tree_cry);
							}else if("smile".equals(getData.feeling)){
								treeFeel.setImageResource(R.drawable.tree_simle);
							}
							
							int allLeafs = Integer
									.parseInt(getData.peibancount);
							if (oldTreeLeft != -1) {
								showOldLeafs(oldTreeLeft);
								if (isVisibility) {
									showNewLeafs(allLeafs
												- oldTreeLeft);
								}
							}else{
								showOldLeafs(allLeafs);
							}
							oldTreeLeft = allLeafs;
							for (int j = 0; j < fruitsLocationX.length; j++) {
								addFruits(j + 1);
							}

							
						}
					}
				}
			});
		} else {
			ShowToast.showShort(getActivity(), R.string.net_break);// 提示无网络
		}
	}
	
	

	class TreeRefreshReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(MContants.CHANGE_CURRENT_CHILD_ACTION)) {
				oldTreeLeft=-1;
				loadingGrowTreeDatas();
				ChildBean myChild = (ChildBean)intent.getSerializableExtra(MContants.CHANGE_CURRENT_CHILD_DATAS);
				treeTitle.setText(myChild.name);
				setMyclassStudentsWindow(myChild);
			}
		}
	}
	
	private void setMyclassStudentsWindow(ChildBean myChild){
		myStudentsWindow = null;
		List<MyClassStudent> dbStudents = cupboard().withDatabase(sqlDb)
				.query(MyClassStudent.class).withSelection("class_id = ?", mSpUtil.getChildClassId()).list();
		myStudentsWindow = new ClassWithStudentsWindow(getActivity(), myChild, dbStudents, this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(receiver);
		//getActivity().unregisterReceiver(leafReceiver);
	}

	@Override
	protected void onChoiceChildResult(ChildBean myChild) {
		treeTitle.setText(myChild.name);
	}

	@Override
	public void onSelectResult(int type, String className,
			MyClassStudent selected) {
		// TODO Auto-generated method stub
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.e("===", "tabGrow onResume");
	}


}
